package com.hq.zb.config;

import com.hq.zb.entity.CurrentUser;
import com.hq.zb.utils.ContextHolderUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Properties;

/**
 * 自定义 Mybatis 插件，自动设置 createdBy，creationDate，lastUpdateDate 和 lastUpdatedBy 的值。
 * 拦截 update 操作（添加和修改）
 * @author huanghanrui
 * @date 2022-03-23
 */
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        if (parameter == null) {
            return invocation.proceed();
        }
        CurrentUser currentUser = ContextHolderUtils.getCurrentUser();
        if (SqlCommandType.INSERT == sqlCommandType) {
            Field[] fields = parameter.getClass().getSuperclass().getDeclaredFields();
            for (Field field : fields) {
                try {
                    if ("createdBy".equals(field.getName())) {
                        if (currentUser.getUserId() != null) {
                            field.setAccessible(true);
                            field.set(parameter, currentUser.getUserId());
                            field.setAccessible(false);
                        }
                    }
                    if ("creationDate".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, new Date());
                        field.setAccessible(false);
                    }
                    if ("lastUpdateDate".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, new Date());
                        field.setAccessible(false);
                    }
                    if ("lastUpdatedBy".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, currentUser.getUserId());
                        field.setAccessible(false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (SqlCommandType.UPDATE == sqlCommandType) {
            Field[] fields = null;
            if (parameter instanceof MapperMethod.ParamMap) {
                MapperMethod.ParamMap<?> p = (MapperMethod.ParamMap<?>) parameter;
                if (p.containsKey("et")) {
                    parameter = p.get("et");
                } else {
                    parameter = p.get("param1");
                }
                if (parameter == null) {
                    return invocation.proceed();
                }
                fields = parameter.getClass().getDeclaredFields();
            } else {
                fields = parameter.getClass().getDeclaredFields();
            }
            for (Field field : fields) {
                try {
                    if ("lastUpdateDate".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, new Date());
                        field.setAccessible(false);
                    }
                    if ("lastUpdatedBy".equals(field.getName())) {
                        field.setAccessible(true);
                        field.set(parameter, currentUser.getUserId());
                        field.setAccessible(false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
